package http;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

// 第一个版本的 http 服务器
public class HttpSeverV1 {
    private ServerSocket serverSocket = null;

    public HttpSeverV1(int port) throws IOException {
        this.serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动");
        ExecutorService executorService = Executors.newCachedThreadPool();
        while(true){
            Socket clientSocket = serverSocket.accept();
            executorService.execute(new Runnable(){

                @Override
                public void run() {
                    processConnection(clientSocket);
                }
            });
        }
    }

    private void processConnection(Socket clientSocket) {
        try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()))) {
            // 在这里进行 http 的操作
            // 1. 解析http请求行
            String httpLine = bufferedReader.readLine();
            System.out.println("==="+httpLine);
            String[] httpLineArray = httpLine.split(" ");
            String requestMethod = httpLineArray[0];
            String requestUrl = httpLineArray[1];
            String requestVersion = httpLineArray[2];

            // 解析http 请求头
            String requestHeader;
            Map<String,String> headers = new HashMap<>();
            while((requestHeader = bufferedReader.readLine()) != null && !"".equals(requestHeader)){
                String[] headerArray = requestHeader.split(": ");
                headers.put(headerArray[0].trim(),headerArray[1].trim());
            }
            String response = "";
            if("/hello".equals(requestUrl)){
                bufferedWriter.write("HTTP/1.1 200 OK\n");
                response ="<h1>你好张帅比!</h1>";
            }else if("/redirect".equals(requestUrl)){
                bufferedWriter.write("HTTP/1.1 307 Temporary Redirect\n");
                bufferedWriter.write("Location: https://www.baidu.com\n");
            }else {
                bufferedWriter.write("HTTP/1.1 404 Not Found\n");
                response = "<h1>没找的资源</h1>";
            }

            bufferedWriter.write("Content-Type: text/html; charset=utf-8\n");
            bufferedWriter.write("Content-Length:"+response.getBytes().length+"\n");
            bufferedWriter.write("\n");
            bufferedWriter.write(response+"\n");
            bufferedWriter.flush();

        } catch (IOException e) {
//            e.printStackTrace();
            System.out.printf("下线");
        }finally{
            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws IOException {
        HttpSeverV1 severV1 = new HttpSeverV1(9090);
        severV1.start();
    }
}
